/*
 * 使用示例:
 * app.use(morgan(options));
 * 
 * options支持的参数:
 * 1、logPath 日志目录地址
 */
'use strict';

const morgan = require('./morgan');
const fs = require('fs');
const path = require('path');
const moment = require('moment');
const FileStreamRotator = require('file-stream-rotator');

// morgan date format
morgan.token('date', function() {
  return moment().format('YYYY-MM-DD HH:mm:ss');
});
// correct request ip
morgan.token('remote-addr', function(req, res) {
  return req._CUSTOM_.ip;
});

exports = module.exports = (options) => {
  fs.existsSync(options.logPath) || fs.mkdirSync(options.logPath);
  var accessLogStream = FileStreamRotator.getStream({
    date_format: 'YYYYMMDD',
    filename: path.join(options.logPath, 'access-%DATE%.log'),
    frequency: 'daily',
    verbose: false
  });
  return !process.env.NODE_ENV || process.env.NODE_ENV === 'development' ?
    morgan('dev') :
    morgan('combined', { stream: accessLogStream });
};